<?php
namespace app\controllers;

use app\commission\ReceivedCommission;
use app\models\order\Order;
use app\models\system\SetBasic;
use app\models\user\UserAccount;
use app\models\user\UserCommission;

class TimeoutReceivedController extends Controller
{
    /**
     * timeout received
     *
     * 30 2 * * * /usr/bin/curl http://nl-api.97app.cn/timeout-received/run
     *
     * /timeout-received/run
     */
    public function actionRun()
    {
        $orders = Order::find()
            ->where(['status' => Order::$statusMapping['WAIT_RECEIVING']])
            // ->orderBy(['id' => SORT_DESC])
            ->all();

        $set = SetBasic::getLastOne();

        $time = time();
        $expired = 3600 * 24 * $set->order_received_timeout;
        // $expired = 1;
        foreach ($orders as $order) {
            $t = $order->create_time;
            $t = strtotime($t);

            if ($time - $t >= $expired) {
                if (ReceivedCommission::done($order->id)) {
                    $order->status = Order::$statusMapping['RECEIVED'];
                    $order->save();
                }
            }
        }
    }

    // 重算佣金, 时间过了的
    public function actionMan()
    {
        $id = $this->get('id');

        if (intval($id) <= 0) {
            return;
        }

        if (ReceivedCommission::done($id)) {
            echo $id, "\n <br />";
        }
    }


    // 两小时取消订单
    // 5分钟执行一次
    // */5 * * * * /usr/bin/curl http://nl-api.97app.cn/timeout-received/cancel
    public function actionCancel()
    {
        $orders = Order::find()
            ->where(['status' => Order::$statusMapping['NON_PAYMENT']])
            ->all();

        $time = time();
        $expired = 3600 * 24 * 0.5; // 30小时取消
        // $expired = 1;
        foreach ($orders as $order) {
            $t = $order->create_time;
            $t = strtotime($t);

            if ($time - $t >= $expired) {

                // todo 要还回余额
                $account = UserAccount::findOne(['user_id' => $order->user_id]);
                if ($account) {
                    if ($account->lock_balance >= $order->use_balance) {
                        $account->balance += $order->use_balance;
                    }
                    if ($account->lock_score >= $order->use_score) {
                        $account->score += $order->use_score;
                    }
                    $account->save();
                }

                // $order->status = Order::$statusMapping['CANCEL'];
                $order->status = Order::$statusMapping['DELETE'];
                $order->save();
            }
        }
    }
}